<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script>
	var googleReader = "http://www.google.com/reader";
	var googleReaderGETRequest = "http://www.google.com/reader/api/0/unread-count?all=true&output=json";
	var requestInterval = 1000 * 60;  // 1 minute
	var requestTimeout = 1000 * 5;  // 5 seconds
	var unreadCount = 0;
			
	function init() {
		window.setTimeout(startRequest, 0);
	}

    // Schedule request
	function scheduleRequest() {
		window.setTimeout(startRequest, requestInterval);
	}
		
	// Starts request	
	function startRequest() {
	    getUnreadCount(
	        function(count) {
		        toggleLoggedInState();
				updateUnreadCount(count);
				scheduleRequest();
			},
			function() {
			    toggleLoggedOutState();
				scheduleRequest();
			}
		);
	}

    // Gets unread count and update label
	function getUnreadCount(onSuccess, onError) {
	    var request = new XMLHttpRequest();	    
	    var abortTimer = window.setTimeout(function() {
	        request.abort();
	        onError()
	    }, requestTimeout);

	    function handleSuccess(count) {
	        window.clearTimeout(abortTimer);
	        onSuccess(count);
	    }

	    function handleError() {
	        window.clearTimeout(abortTimer);
	        onError();
	    }

	    try {
	        console.log("Request...");
	        request.onreadystatechange = function() {
	            console.log("ReadyState = " + request.readyState);
	            if (request.readyState == 4) {
	                if (request.status == 200) {
	                    if (!IsJSONResponse(request.getResponseHeader("Content-Type"))) {
	                        handleError();
	                        return;
	                    }

	                    // Parse json
	                    var readerInfo = eval("(" + request.responseText + ")");
	                    // Temp var for count of unread items
	                    var count = 0;

	                    // Read number of unread items. It contains in an object whose id contains string "reading-list"
	                    for (var i = 0; i < readerInfo.unreadcounts.length; i++) {
	                        if (readerInfo.unreadcounts[i].id.search("reading-list") != -1) {
	                            count = readerInfo.unreadcounts[i].count;
	                            break;
	                        }
	                    }

	                    handleSuccess(count);
	                } else {
	                    handleError();
	                }
	            }
	        }

	        request.onerror = function(error) {
	            console.log("Error");
	            console.log(error);
	            handleError();
	        }

	        // Create and send the request
	        request.open("GET", googleReaderGETRequest);
	        request.send(null);
	    }

	    catch (e) {
	        console.log("ex: " + e);
	        console.error("exception: " + e);
	        handleError();
	    }
	}

	function IsJSONResponse(responseType) {
	    return (responseType != "text/json" || 
	            responseType != "text/javascript" ||
	            responseType != "application/javascript" || 
	            responseType != "application/x-javascript");
	}

    // Opens Google Reader in new tab
	function goToGoogleReader() {
	    chrome.tabs.create({ url: googleReader });
	}
	
	// Updates label
	function updateUnreadCount(count) {
        if (unreadCount != count) {
            unreadCount = count;
            startFlip();
        }
    }

    // Shows logged in state = works good
    function toggleLoggedInState() {
        document.getElementById("notLoggedIn").style.display = "none";
        document.getElementById("loggedIn").style.display = "";
    }

    // Shows logged out stade = you should logged in
    function toggleLoggedOutState() {
        document.getElementById("loggedIn").style.display = "none";
        document.getElementById("notLoggedIn").style.display = "";
    }
    
    // animations
    function startFlip() {
        document.getElementById("unreadCount").className = 'mid-flip';
        setTimeout(midFlip, 500);
    }

    function midFlip() {
        document.getElementById("unreadCount").className = 'post-flip';  
        document.getElementById("unreadCount").innerHTML = "(" + unreadCount + ")";
        setTimeout(endFlip, 500);
    }

    function endFlip() {
        document.getElementById("unreadCount").className = 'base-flip';  
    }

</script>
</head>

<body onload="init()" onclick="goToGoogleReader()">
  <div class="toolstrip-button">
    <img src="reader.ico" style="width:auto; height:auto">
    <span id="notLoggedIn" style="display:none;">Login</span>
    <span id="loggedIn">Google Reader <span style="display: inline-block;" id="unreadCount" class="base-flip"></span></span>
  </div>
</body>
</html>